package com.kangyi.user.service.Impl;

import cn.hutool.core.collection.CollUtil;
import com.kangyi.constant.MessageConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.dto.ActivitySignupDTO;
import com.kangyi.entity.ActivitySignup;
import com.kangyi.exception.ActivitySignupException;
import com.kangyi.exception.DataNotExistException;
import com.kangyi.user.mapper.ActivitySignupMapper;
import com.kangyi.user.mapper.PublicActivityImgMapper;
import com.kangyi.user.service.ActivitySignupService;
import com.kangyi.utils.AuthUtil;
import com.kangyi.vo.ActivitySignupCountVO;
import com.kangyi.vo.ActivitySignupVO;
import com.kangyi.vo.PublicActivityImgVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Blank
 * @version 1.0
 */
@Service
public class ActivitySignupServiceImpl implements ActivitySignupService {

    @Autowired
    private ActivitySignupMapper activitySignupMapper;

    @Autowired
    private PublicActivityImgMapper publicActivityImgMapper;
    @Override
    public List<ActivitySignupVO> inquiryActivitySignup(Integer userId) {
        // 1️ 查询报名记录（主 SQL 查询）
        List<ActivitySignupVO> activitySignupVOList = activitySignupMapper.inquiryActivitySignup(userId);

        // 2 先判断数据是否为空，避免无意义循环
        if (CollUtil.isEmpty(activitySignupVOList)) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }

        // 3 收集所有活动 ID（避免 N+1 查询）
        List<Integer> publicActivityIds = activitySignupVOList.stream()
                .map(activitySignupVO -> activitySignupVO.getPublicActivityVO() != null ? activitySignupVO.getPublicActivityVO().getId() : null)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        if (CollUtil.isNotEmpty(publicActivityIds)) {
            // 4 批量查询所有活动的图片信息
            List<PublicActivityImgVO> publicActivityImgVOS = publicActivityImgMapper.inquiryPublicActivityImgBatch(publicActivityIds);

            // 5 将图片数据按活动 ID 进行分组
            Map<Integer, List<PublicActivityImgVO>> imgMap = publicActivityImgVOS.stream()
                    .collect(Collectors.groupingBy(PublicActivityImgVO::getPublicActivityId));

            // 6 统计此活动报名总人数
            List<ActivitySignupCountVO> signupCounts = activitySignupMapper.countTotal(publicActivityIds);
            Map<Integer, Integer> countMap = signupCounts.stream()
                    .collect(Collectors.toMap(ActivitySignupCountVO::getActivityId, ActivitySignupCountVO::getTotal));

            // 7 遍历报名数据，填充相关数据
            for (ActivitySignupVO activitySignupVO : activitySignupVOList) {
                if (activitySignupVO.getPublicActivityVO() != null) {
                    Integer activityId = activitySignupVO.getPublicActivityVO().getId();
                    activitySignupVO.getPublicActivityVO().setPublicActivityImgVOList(imgMap.getOrDefault(activityId, new ArrayList<>()));
                    activitySignupVO.getPublicActivityVO().setTotal(countMap.getOrDefault(activityId, 0)); // 设置报名总人数
                }
            }
        }

        return activitySignupVOList;
    }

    @Override
    public void signUpActivity(ActivitySignupDTO activitySignupDTO) {

        //查询是否有过报名
        ActivitySignup activitySignup = activitySignupMapper.getByGuestsStayingIdAndActivityId(activitySignupDTO.getGuestsStayingId(),activitySignupDTO.getActivityId());
        if (activitySignup != null) {
            throw new ActivitySignupException(MessageConstant.YOU_HAVE_ALREADY_REGISTERED_FOR_THIS_EVENT);
        }
        //设置报名状态，时间
        ActivitySignup build = ActivitySignup.builder()
                .activityId(activitySignupDTO.getActivityId())
                .guestsStayingId(activitySignupDTO.getGuestsStayingId())
                .userId(activitySignupDTO.getUserId())
                .signupTime(LocalDateTime.now())
                .status(ActivitySignup.PENDING_REVIEW)
                .build();
        //报名
        activitySignupMapper.signUpActivity(build);
    }

    @Override
    public void deleteActivitySignup(Integer id) {
        Integer currentId = BaseContext.getCurrentId();
        AuthUtil.validateUserPermission(currentId);

        ActivitySignup activitySignup = activitySignupMapper.getById(id);
        if (activitySignup == null) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }

        activitySignupMapper.deleteActivitySignup(id);
    }


}
